﻿using CCWin;
using ERPWinFormWork.Produce.ErrorCode;
using ERPWinFormWork.Produce.Produce.Dtos;
using ERPWinFormWork.Sales;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Produce
{
    public partial class Production_PlanForm : Form
    {
        private ApiClient _apiClient;

        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalPages { get; set; } = 1;
        private int TotalSize { get; set; }


        public Production_PlanForm()
        {
            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            dgvProduction_PlanData.CellContentClick += dgvProduction_PlanData_CellContentClick;
            GetData();
            LoadcboSource_TypeData();
        }

        

        private async void dgvProduction_PlanData_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                Production_PlanDtos item = dgvProduction_PlanData.Rows[e.RowIndex].DataBoundItem as Production_PlanDtos;
                if (item != null)
                {
                    string colName = dgvProduction_PlanData.Columns[e.ColumnIndex].Name;
                    if (colName == "Details")
                    {
                        new DiscountDetailsForm(item.Id).ShowDialog();
                    }
                    else if (colName == "Edit")
                    {
                        // 打开编辑窗口并回填
                   
                        CreateProduction_Plan form1 = new CreateProduction_Plan(this, item.Id);
                        form1.Show();



                    }
                    else if (colName == "Delete")
                    {
                        if (MessageBox.Show("确认删除此生产计划吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            var data = new { id = item.Id };
                            var response = await _apiClient.PostAsync<object, ApiResponse<string>>("Production_Plan/DelProduction_PlanHandle", data);
                            if (response != null && response.code == 200)
                            {
                                MessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                GetData();
                            }
                            else
                            {
                                MessageBox.Show($"删除失败: {response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
        }



        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        public async void GetData()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Plan_Number", this.txtPlan_Number.Text.Trim()},
                    { "Source_Type", this.cboSource_Type.Text.Trim() },
                    { "Product_Name",this.txtProduct_Name.Text.Trim() },

                };


            var response = await _apiClient.GetAsync<ApiResponse<List<Production_PlanDtos>>>(
                    endpoint: "Production_Plan/GetProduction_PlanHandle",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvProduction_PlanData.DataSource = response.pageData;
                TotalPages = response.totalCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblcount.Text = TotalSize.ToString();
                AddOperationColumns();

                // 添加序号列作为第一列
                if (dgvProduction_PlanData.Columns["SerialNo"] == null)
                {
                    DataGridViewTextBoxColumn serialCol = new DataGridViewTextBoxColumn();
                    serialCol.Name = "SerialNo";
                    serialCol.HeaderText = "序号";
                    serialCol.ReadOnly = true;
                    dgvProduction_PlanData.Columns.Insert(0, serialCol); // 插入为第一列
                }

                // 填充序号（全局索引，正序）
                for (int i = 0; i < dgvProduction_PlanData.Rows.Count; i++)
                {
                    int serial = (PageIndex - 1) * PageSize + i + 1;
                    dgvProduction_PlanData.Rows[i].Cells["SerialNo"].Value = serial;
                }

                // 隐藏Id列
                if (dgvProduction_PlanData.Columns["Id"] != null)
                {
                    dgvProduction_PlanData.Columns["Id"].Visible = false;
                }

                dgvProduction_PlanData.ScrollBars = System.Windows.Forms.ScrollBars.Both; // Ensure scrollbars are enabled after binding
                dgvProduction_PlanData.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; // Auto-size columns to fit content, enable horizontal scroll if needed
            }

        }

        private void AddOperationColumns()
        {
            string[] columnNames = {  "Delete", "Edit" };
            string[] headerTexts = {  "删除","编辑" };

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (dgvProduction_PlanData.Columns[columnNames[i]] == null)
                {
                    var col = new DataGridViewButtonColumn();
                    col.Name = columnNames[i];
                    col.HeaderText = headerTexts[i];
                    col.Text = headerTexts[i];
                    col.UseColumnTextForButtonValue = true;
                    col.ReadOnly = false;
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    dgvProduction_PlanData.Columns.Add(col);
                }
            }
        }



        private void btncreate_Click(object sender, EventArgs e)
        {
            CreateProduction_Plan form1 = new CreateProduction_Plan(this);
            form1.Show();
        }


        private void LoadcboSource_TypeData()
        {
            // 模拟一个数据源，这里是简单的字符串列表，实际可从数据库等获取
            List<string> addressList = new List<string>()
            {
                "销售订单",
                "库存备货",
                "其他",
            };

            // 清空ComboBox原有项（可选，避免重复添加）
            cboSource_Type.Items.Clear();
            // 将数据源的数据添加到ComboBox中
            cboSource_Type.Items.AddRange(addressList.ToArray());

            // 可选：设置默认选中项，比如选第一个
            if (cboSource_Type.Items.Count > 0)
            {
                cboSource_Type.SelectedIndex = -1;
            }
        }


        private void cboSource_Type_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboSource_Type.SelectedItem != null)
            {
                string selectedAddress = cboSource_Type.SelectedItem.ToString();
                // MessageBox.Show($"你选择的地址是：{selectedAddress}");
            }
            //else
            //{
            //    MessageBox.Show("请选择一个地址");
            //}
        }

        private void btnPreviousPage_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void btnNextpage_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        private void btnreset_Click(object sender, EventArgs e)
        {
            txtPlan_Number.Clear();
            txtProduct_Name.Clear();
            cboSource_Type.SelectedIndex = -1;
            GetData();

        }

        private void btnGetWhere_Click(object sender, EventArgs e)
        {
            GetData();
        }

    

        private void 工单任务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Work_TaskFrom form1 = new Work_TaskFrom();
            form1.Show();
        }

        private void 报工记录ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void 生产计划ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void dgvProduction_PlanData_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
